# 为了能在外部脚本中调用Django ORM模型，必须配置脚本环境变量，将脚本注册到Django的环境变量中
# import os
# import django
#
# # 第一个参数固定，第二个参数是工程名称.settings
# os.environ.setdefault('DJANGO_SETTING_MODULE', 'piDjango.settings')
# django.setup()

import sys
import time

from pymata4 import pymata4

# 引入mqtt包
import paho.mqtt.client as mqtt
# 使用独立线程运行
from threading import Thread

import json


# from message.models import MqttMessage


def reloadPage():
    print("刷新页面")
    # client.publish("reloadFetch", payload=None, qos=0, retain=False)


board = pymata4.Pymata4()




def i2cCallPwd(my_board,pin):
    my_board.set_pin_mode_i2c()
    my_board.i2c_write(pin, [0,0])

def i2cCallstepper(my_board,pin,xstepper,ystepper):
    my_board.set_pin_mode_i2c()
    my_board.i2c_write(pin, [xstepper, ystepper])



def servo(my_board, pin, start ,end ):
    """
    Set a pin to servo mode and then adjust
    its position.

    :param end:
    :param start: 脉冲开始 脉冲结束
    :param my_board: pymata4
    :param pin: pin to be controlled
    """

    # set the pin mode
    my_board.set_pin_mode_servo(pin)

    # set the servo to 0 degrees
    my_board.servo_write(pin, start)

    # my_board.set_pin_mode_i2c()
    # my_board.i2c_write(pin, [start, end])






# 建立mqtt连接
def on_connect(client, userdata, flag, rc):
    print("Connect with the result code " + str(rc))
    client.subscribe('mqtt/4b-01', qos=2)


# 接收、处理mqtt消息
def on_message(client, userdata, msg):
    out = str(msg.payload.decode('utf-8'))
    print(msg.topic)


    mqttJsonMessage = json.loads(out)
    print(mqttJsonMessage)
    if mqttJsonMessage["gear"] == "steeringEngine":
        print("舵机驱动")
        servo(board, int(mqttJsonMessage["pin"]), int(mqttJsonMessage["start"]),0)
    if mqttJsonMessage["gear"] == "electromagnet":
        i2cCallPwd(board,int(mqttJsonMessage["pin"]))
    if mqttJsonMessage["gear"] == "stepper":
        i2cCallstepper(board,int(mqttJsonMessage["pin"]),int(mqttJsonMessage["start"]),int(mqttJsonMessage["end"]))



    # set_intensity(board, 9)
    # servo(board,5,out)
    # servo(board, 6, out)
    # out = json.loads(out)
    # # if out["msg"] == "offline":
    # #     print(out["location"],"的",out["user"],'于',out['time'],"离线")
    # #
    # #
    # # # 收到消息后执行任务
    # # if msg.topic == 'test/newdata':
    # #     print(out)
    #
    # if(out['msg']=='outOfBattery'or out['msg']=="water"):
    #     mqttMessage = MqttMessage(message=out['msg'], senesor=out['sensor'], location=out['location'])
    #     mqttMessage.save()


# mqtt客户端启动函数
def mqttfunction():
    global client
    # 使用loop_start 可以避免阻塞Django进程，使用loop_forever()可能会阻塞系统进程
    # client.loop_start()
    # client.loop_forever() 有掉线重连功能
    client.loop_forever(retry_first_connection=True)


client = mqtt.Client(client_id="4b-01", clean_session=False)


# 启动函数
def mqtt_run():
    client.on_connect = on_connect
    client.on_message = on_message
    # 绑定 MQTT 服务器地址
    broker = '47.102.200.101'
    # MQTT服务器的端口号
    client.connect(broker, 1883, 60)
    client.username_pw_set('admin', 'qmy980902')
    client.reconnect_delay_set(min_delay=1, max_delay=2000)
    # 启动
    mqttthread = Thread(target=mqttfunction)
    mqttthread.start()

    # sched = BlockingScheduler()
    # sched.add_job(reloadPage, 'interval', seconds=5)
    # sched.start()


# 启动 MQTT
# mqtt_run()


if __name__ == "__main__":
    mqtt_run()
